#include "sphere.h"
double noise(double x, double y, double z);

/*-<==>-----------------------------------------------------------------
/ Constructor
/----------------------------------------------------------------------*/
CSphere::CSphere(SCALAR a_radius) 
: radius( a_radius ) {
}

/*-<==>-----------------------------------------------------------------
/ 
/----------------------------------------------------------------------*/
bool CSphere::hits (const CLine &line, SCALAR &t_hit) {
	VECTOR dst = line.loc - loc;
	SCALAR b_prima = dst.dot(line.dir);
	SCALAR c = dst.dot(dst) - radius*radius;
	SCALAR d = b_prima*b_prima - c;
	if(d<0)
		return false;
	else
	{
		double sqrtD = sqrt(d);
		SCALAR t_menys = -b_prima -sqrtD;
		if(t_menys > SMALL_AMOUNT)
		{
			t_hit = t_menys;
			return true;
		}
		SCALAR t_mes = -b_prima + sqrtD;
		if(t_mes > SMALL_AMOUNT)
		{
			t_hit = t_mes;
			return true;
		}
	}

  return false;
}



/*-<==>-----------------------------------------------------------------
/ 
/----------------------------------------------------------------------*/
bool CSphere::hits (const CLine &line, SCALAR &t_hitIn, SCALAR &t_hitOut) {
	VECTOR dst = line.loc - loc;
	SCALAR b_prima = dst.dot(line.dir);
	SCALAR c = dst.dot(dst) - radius*radius;
	SCALAR d = b_prima*b_prima - c;
	bool intersects = false;
	if(d<0)
		return false;
	else
	{
		bool in = true;
		SCALAR sqrtD = sqrt(d);	
		SCALAR t_menys = -b_prima - sqrtD;
		SCALAR t_mes = -b_prima + sqrtD;
		
		if(t_menys > SMALL_AMOUNT && t_mes > SMALL_AMOUNT )
		{
			if(t_menys < t_mes)
			{
				t_hitIn= t_menys;
				t_hitOut = t_mes;
				intersects = true;
			}
			else{
				t_hitIn= t_mes;
				t_hitOut = t_menys;
				intersects = true;

			}
		}
	}
	
  return intersects;
}

VECTOR CSphere::getNormal(const VECTOR &hit_loc) {
	VECTOR normal = hit_loc - loc;
	normal = normal/radius;

	if(material->bumpMap)
	{
		 material->bumpNormal(hit_loc,normal);
	}
	return normal;
}

